package com.xiaozhi.dialogue.tts.providers;// ... existing code ...
import cn.hutool.core.util.StrUtil;
// Deleted:import com.alibaba.dashscope.aigc.multimodalconversation.AudioParameters;
// Deleted:import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
// Deleted:import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
// Deleted:import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
// Deleted:import com.alibaba.dashscope.audio.tts.SpeechSynthesisAudioFormat;
// Deleted:import com.alibaba.dashscope.audio.tts.SpeechSynthesisParam;
// Deleted:import com.alibaba.dashscope.audio.tts.SpeechSynthesizer;
import com.alibaba.nls.client.AccessToken;
import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.OutputFormatEnum;
import com.alibaba.nls.client.protocol.SampleRateEnum;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizer;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerListener;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerResponse;
import com.xiaozhi.dialogue.tts.TtsService;
import com.xiaozhi.entity.SysConfig;
// Deleted:import com.xiaozhi.utils.AudioUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
// Deleted:import java.io.InputStream;
// Deleted:import java.net.URL;
import java.nio.ByteBuffer;
import java.util.UUID;
import java.util.concurrent.*;

public class AliyunTtsNewService implements TtsService {
    private static final Logger logger = LoggerFactory.getLogger(AliyunTtsNewService.class);

    private static final String PROVIDER_NAME = "aliyun";
    // 添加重试次数常量
    private static final int MAX_RETRY_ATTEMPTS = 3;
    // 添加重试间隔常量（毫秒）
    private static final long RETRY_DELAY_MS = 1000;
    // 添加TTS操作超时时间（秒）
    private static final long TTS_TIMEOUT_SECONDS = 5;

    // 使用共享的线程池，避免频繁创建和销毁
    private static final ExecutorService sharedExecutor = Executors.newCachedThreadPool();

    private final String accessKeyId;
    private final String accessKeySecret;
    private final String voiceName;
    private final int speechRate;
    private final String outputPath;
    private NlsClient client;

    public AliyunTtsNewService(SysConfig config,
                               String voiceName,int speechRate, String outputPath) {
        // Deleted:this.apiKey = config.getApiKey();
        // 假设SysConfig中有accessKeyId和accessKeySecret字段
        this.accessKeyId = "LTAI5tFSpEuFVeCj8CVqGFCU"; // 需要根据实际字段名调整
        this.accessKeySecret = "Vsvs9UcVfF1kiBL9LDthKg5WwP9aQS"; // 需要根据实际字段名调整
//         this.accessKeyId = config.getAk(); // 需要根据实际字段名调整
//         this.accessKeySecret = config.getSk(); // 需要根据实际字段名调整


        System.out.println("voiceName: " + voiceName);
        System.out.println("speechRate: " + speechRate);
         this.voiceName = voiceName;
         // 语速
         this.speechRate = speechRate;
         this.outputPath = outputPath;
        // 初始化NlsClient
        try {
            // 使用AccessToken机制初始化NlsClient
            AccessToken accessToken = new AccessToken(accessKeyId, accessKeySecret);
            accessToken.apply();
            this.client = new NlsClient(accessToken.getToken());
        } catch (Exception e) {
            logger.error("初始化NlsClient失败", e);
        }
    }

    @Override
    public String getProviderName() {
        return PROVIDER_NAME;
    }

    @Override
    public String textToSpeech(String text) throws Exception {
        return ttsWithNls(text);
    }

    // 使用NLS SDK进行语音合成
    private String ttsWithNls(String text) {

        if (client == null) {
            logger.error("NlsClient未正确初始化，无法进行语音合成");
            return StrUtil.EMPTY;
        }

        // 检查输入文本是否为空
        if (StrUtil.isBlank(text)) {
            logger.error("语音合成文本不能为空");
            return StrUtil.EMPTY;
        }
        // 阿里云TTS要求文本长度至少为1个字符，处理一些特殊字符
        if (text.length() < 1) {
            logger.warn("语音合成文本长度不足，添加默认文本 - 原始文本: \"{}\"", text);
            text = "。"; // 添加一个默认字符以满足最小长度要求
        }


        int attempts = 0;
        while (attempts < MAX_RETRY_ATTEMPTS) {
            SpeechSynthesizer synthesizer = null;
            try {
                String outPath = outputPath + getAudioFileName();
                File file = new File(outPath);

                // 创建语音合成监听器
                SpeechSynthesizerListener listener = new SpeechSynthesizerListener() {
                    FileOutputStream fos = new FileOutputStream(file);

                    // 语音合成的语音二进制数据
                    @Override
                    public void onMessage(ByteBuffer message) {
                        try {
                            byte[] bytesArray = new byte[message.remaining()];
                            message.get(bytesArray, 0, bytesArray.length);
                            fos.write(bytesArray);
                        } catch (IOException e) {
                            logger.error("写入音频数据失败", e);
                        }
                    }

                    // 语音合成结束
                    @Override
                    public void onComplete(SpeechSynthesizerResponse response) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            logger.error("关闭文件输出流失败", e);
                        }
                    }

                    @Override
                    public void onFail(SpeechSynthesizerResponse response) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            logger.error("关闭文件输出流失败", e);
                        }
                        logger.error("语音合成失败: task_id: " + response.getTaskId() +
                                ", status: " + response.getStatus() +
                                ", status_text: " + response.getStatusText());
                    }
                };

                // 创建实例，建立连接
                synthesizer = new SpeechSynthesizer(client, listener);
                // 设置AppKey，需要从配置中获取
                synthesizer.setAppKey("cayHaQuXAOJyuB4g");
                // 设置返回音频的编码格式
                synthesizer.setFormat(OutputFormatEnum.WAV);
                // 设置返回音频的采样率
                synthesizer.setSampleRate(SampleRateEnum.SAMPLE_RATE_16K);
                // 发音人
                synthesizer.setVoice(voiceName);
                System.out.println("实际的voiceNamevoiceNamevoiceName"+voiceName);
                // 语调，范围是-500~500，可选，默认是0
                synthesizer.setPitchRate(100);
                // 语速，范围是-500~500，默认是0
                synthesizer.setSpeechRate(speechRate);
                // 设置用于语音合成的文本
                synthesizer.setText(text);
                // 是否开启字幕功能（返回相应文本的时间戳），默认不开启
                synthesizer.addCustomedParam("enable_subtitle", false);

                // 此方法将以上参数设置序列化为JSON格式发送给服务端，并等待服务端确认
                long start = System.currentTimeMillis();
                synthesizer.start();
                logger.info("tts start latency " + (System.currentTimeMillis() - start) + " ms");

                // 等待语音合成结束
                synthesizer.waitForComplete();
                logger.info("tts stop latency " + (System.currentTimeMillis() - start) + " ms");

                return outPath;
            } catch (Exception e) {
                attempts++;
                if (attempts < MAX_RETRY_ATTEMPTS) {
                    logger.warn("语音合成aliyun - 使用{}模型失败，正在重试 ({}/{}): {}",
                            voiceName, attempts, MAX_RETRY_ATTEMPTS, e.getMessage());
                    try {
                        // 等待一段时间后重试
                        TimeUnit.MILLISECONDS.sleep(RETRY_DELAY_MS);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        logger.error("重试等待被中断", ie);
                        return StrUtil.EMPTY;
                    }
                } else {
                    logger.error("语音合成aliyun - 使用{}模型失败，已达到最大重试次数：", voiceName, e);
                    return StrUtil.EMPTY;
                }
            } finally {
                // 关闭连接
                if (null != synthesizer) {
                    synthesizer.close();
                }
            }
        }
        return StrUtil.EMPTY;
    }

}
